package org.springblade.modules.system.utils;

/**
 * @description: 脱敏工具
 * @author: luoyt
 * @create: 2024-08-16 21:14
 **/
public class DataMaskingUtil {

    /**
     * 姓名脱敏：三个或四个字符保留首尾，两个字符保留首
     * @param name 姓名
     * @return String
     */
    public static String maskName(String name) {
        if (name == null || name.isEmpty()) {
            return name;
        }
        if (name.length() == 2) {
            return name.charAt(0) + "*";
        } else if (name.length() > 2) {
            StringBuilder maskedName = new StringBuilder();
            maskedName.append(name.charAt(0));
            for (int i = 1; i < name.length() - 1; i++) {
                maskedName.append("*");
            }
            maskedName.append(name.charAt(name.length() - 1));
            return maskedName.toString();
        } else {
            return name;  // 对于一个字符的名字不做处理
        }
    }

    /**
     * 身份证号脱敏：显示前2位和后4位，中间用星号代替
     * @param idCard 身份证号
     * @return String
     */
    public static String maskIdCard(String idCard) {
        if (idCard == null || idCard.length() < 18) {
            return idCard;
        }
        StringBuilder maskedIdCard = new StringBuilder();
        maskedIdCard.append(idCard.substring(0, 2));
        for (int i = 2; i < idCard.length() - 4; i++) {
            maskedIdCard.append("*");
        }
        maskedIdCard.append(idCard.substring(idCard.length() - 4));
        return maskedIdCard.toString();
    }

    /**
     * 手机号脱敏，留首2尾4
     * @param phoneNumber 手机号
     * @return String
     */
    public static String maskPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.length() <= 8) {
            return phoneNumber;
        }

        String prefix = phoneNumber.substring(0, 2);
        String suffix = phoneNumber.substring(phoneNumber.length() - 4);

        StringBuilder maskedNumber = new StringBuilder();
        maskedNumber.append(prefix);
        for (int i = 0; i < phoneNumber.length() - 6; i++) {
            maskedNumber.append('*');
        }
        maskedNumber.append(suffix);

        return maskedNumber.toString();
    }
}